package com.LeetCode.StackAndHeap;

import org.junit.Assert;
import org.junit.Test;

import java.util.Stack;

/**
 * 有效括号
 */
public class isValid {
    public boolean isValid(String s) {
        if(s.length() == 0) return true;
        Stack<Character> stack = new Stack<>();
        char[] chars = s.toCharArray();
        stack.push(chars[0]);
        for(int i = 1; i<chars.length; i++){
            char c = chars[i];
            if(c == '{' || c == '[' || c == '(')
                stack.push(c);
            else if ( c == '}' && stack.size()>0 && stack.peek() == '{'){
                stack.pop();
            }else if(c == ']' && stack.size()>0 && stack.peek() == '['){
                stack.pop();
            }else if(c == ')' && stack.size()>0 && stack.peek() == '('){
                stack.pop();
            }else{
                return false;
            }
        }
        return stack.isEmpty();
    }

    @Test
    public void test(){
        Assert.assertTrue(isValid("{[]}"));
        Assert.assertFalse(isValid("([)]"));
        Assert.assertTrue(isValid("()[]{}"));
    }
}
